<?php
/*
+--------------------------------------------------------------------------
|   Anwsion [#RELEASE_VERSION#]
|   ========================================
|   by Tatfook Network Team
|   (c) 2011 - 2012 Anwsion Software
|   http://www.anwsion.com
|   ========================================
|   Support: zhengqiang@gmail.com
|   
+---------------------------------------------------------------------------
*/

class topic_class extends AWS_MODEL
{
	/**
	 * 
	 * 根据指定条件获取话题数据
	 * @param string $where
	 * @param int    $limit
	 * 
	 * @return array
	 */
	public function get_topic_list($where = '', $limit = 10, $return_count = false)
	{
		if ($return_count)
		{
			return $this->count('topic', $where);
		}
		else
		{
			return $this->fetch_all('topic', $where, 'topic_id DESC', $limit);
		}
	}

	/**
	 * 
	 * 根据用户 ID, 得到用户关注话题列表
	 * @param int $uid
	 * 
	 * @return array(
	 * 		topic_title,       //话题标题
	 *	    add_time,          //添加时间
	 *		add_uid,           //添加用户ID
	 *		discuss_count,       //问题总数
	 *		match_id,          //比赛ID
	 *		topic_description, //话题描述
	 *		topic_pic,         //话题图片
	 */
	public function get_focus_topic_list($count = false, $uid = 0, $limit = 20)
	{
		$uid = intval($uid);
		
		if ($uid == 0)
		{
			return array();
		}
		
		if ($count)
		{
			return $this->count('topic_focus', 'uid = ' . $uid);
		}
		else
		{
			$sql = "SELECT tp.* FROM " . $this->get_table('topic') . " AS tp RIGHT JOIN " . $this->get_table("topic_focus") . " AS t ON t.topic_id = tp.topic_id WHERE t.uid = " . $uid . " ORDER BY t.focus_id DESC";
			
			return $this->query_all($sql, $limit);
		}
	}

	/**
	 * 
	 * 根据话题ID,得到子类话题 
	 * @param int $topic_id
	 * 
	 * @return array
	 */
	public function get_topic_childs($topic_id, $limit = '')
	{
		$topic_id = intval($topic_id);
		
		if ($topic_id == 0)
		{
			return false;
		}
		
		$sql = "SELECT topic_title, topic_id FROM " . $this->get_table('topic') . " WHERE parent_id = " . intval($topic_id);
		
		return $this->query_all($sql, $limit);
	}
	
	//获取话题图片
	function get_pic_url($topic_id = 0, $size = 'mid', $pic_file = null)
	{
		if (! $pic_file)
		{
			return false;
		}
		else
		{
			return str_replace(AWS_APP::config()->get('image')->topic_thumbnail['min']['w'] . '_' . AWS_APP::config()->get('image')->topic_thumbnail['min']['h'], AWS_APP::config()->get('image')->topic_thumbnail[$size]['w'] . '_' . AWS_APP::config()->get('image')->topic_thumbnail[$size]['h'], $pic_file);
		}
	}
	
	/**
	 * 批量获取话题标题
	 * @param array $topic_ids
	 * 
	 * @return array
	 */
	public function get_topic_title(array $topic_ids)
	{
		$sql = 'SELECT topic_id, topic_title,topic_pic FROM ' . $this->get_table('topic') . " WHERE topic_id IN (" . implode(",", $topic_ids) . ")";
		
		return $this->query_all($sql);
	}

	/**
	 * 
	 * 得到单条话题内容
	 * @param int $topic_id 话题ID
	 * 
	 * @return array
	 */
	public function get_topic($topic_id)
	{
		static $topics;
		
		if (!$topic_id)
		{
			return false;
		}
		
		if (! $topics[$topic_id])
		{
			$topics[$topic_id] = $this->fetch_row('topic', 'topic_id = ' . intval($topic_id));
		}
		
		return $topics[$topic_id];
	}
	
	/**
	 * 批量获取话题
	 * @param  $topic_array
	 */
	public function get_topics($topic_array)
	{
		if (!is_array($topic_array))
		{
			return array();
		}
		
		return $this->fetch_all('topic', 'topic_id IN(' . implode(',', $topic_array) . ')',' topic_id DESC');
	}

	/**
	 * 获取单条话题-通过话题名称
	 * @param  $topic_title 
	 */
	public function get_topic_by_title($topic_title)
	{
		if (! $topic_title)
		{
			return false;
		}
		
		static $topics;
		
		if (!$topics[$topic_title])
		{  
			
			$topics[$topic_title] = $this->fetch_row('topic', "topic_title = '" . $this->quote($topic_title) . "'");
			
		}
	
		return $topics[$topic_title];
	}

	/**
	 * 获取单条话题id-通过话题名称
	 * @param  $topic_title
	 */
	public function get_topic_id_by_title($topic_title)
	{
		if (! $topic_title)
		{
			return false;
		}
		
		$topic = $this->get_topic_by_title($topic_title);
		
		return $topic['topic_id'];
	}

	/**
	 * 
	 * 得到话题关注数量
	 * @param array $topic_ids
	 * 
	 * @return int 
	 */
	public function get_topic_focus_count(array $topic_ids)
	{
		if (empty($topic_ids))
		{
			return 0;
		}
		
		return $this->count('topic_focus', 'topic_id IN(' . implode(',', $topic_ids) . ')');
	}

	/**
	 * 
	 * 增加话题内容
	 * @param int    $question_id       //操作附加ID,如话题就为话题ID,比赛就为比赛ID
	 * @param string $topic_title       //话题标题
	 * @param int    $add_uid           //添加用户ID
	 * @param int    $discuss_count       //问题总数
	 * @param int    $competitions_id   //比赛ID
	 * @param string $topic_description //话题描述
	 * @param string $topic_pic         //话题图片
	 * @param int    $topic_lock        //话题是否锁定
	 * @param in     $topic_type        //1添加问题话题  2添加话题话题 3比赛话题
	 * 
	 * @return boolean true|false
	 */
	public function save_topic($question_id = 0, $topic_title, $add_uid = 0, $discuss_count = 0, $topic_description = '', $topic_pic = '', $topic_lock = 0, $topic_type = 1)
	{
		if (! $add_uid)
		{
			return false;
		}
		
		//判断是否存在话题
		$topic_id = $this->has_topic($topic_title);
		$question_id = intval($question_id);
		//$competition_id = intval($competition_id);
		$retval = false;
		
		if ($topic_id)
		{
			//添加问题添加到话题的动作
			if ($question_id > 0)
			{
				ACTION_LOG::save_action($add_uid, $question_id, ACTION_LOG::CATEGORY_QUESTION, ACTION_LOG::ADD_TOPIC, $topic_title, $topic_id);
			}
			
			return $topic_id;
		}
		
		//判断话题是否锁定
		if ($this->has_lock_topic($topic_id))
		{
			return false;
		}
		
		$data = array(
			'topic_title' => strip_tags(trim($topic_title)), 
			'add_time' => time(), 
			'add_uid' => intval($add_uid), 
			'discuss_count' => intval($discuss_count), 
			'topic_description' => htmlspecialchars(trim($topic_description)), 
			'topic_pic' => htmlspecialchars(trim($topic_pic)), 
			'topic_lock' => intval($topic_lock)
		);
		
		//更新用户话题数量
		$topic_id = $this->insert('topic', $data);
		
		//记录日志
		if ($topic_type == 1)
		{
			//添加问题添加到话题的动作
			ACTION_LOG::save_action($add_uid, $question_id, ACTION_LOG::CATEGORY_QUESTION, ACTION_LOG::ADD_TOPIC, $topic_title, $topic_id);
			ACTION_LOG::save_action($add_uid, $topic_id, ACTION_LOG::CATEGORY_TOPIC, ACTION_LOG::ADD_TOPIC, $topic_title, $question_id);
		}
		else if ($topic_type == 2)
		{
			// 添加相关话题
			//ACTION_LOG::save_action(USER::get_client_uid(), $topic_id, ACTION_LOG::CATEGORY_TOPIC, ACTION_LOG::ADD_TOPIC_PARENT, $topic_title, '');
		}
		else if ($topic_type == 3)
		{
			ACTION_LOG::save_action($add_uid, $topic_id, ACTION_LOG::CATEGORY_TOPIC, ACTION_LOG::ADD_TOPIC, $topic_title, '');
		}
		
		return $topic_id;
	}

	/**
	 * 
	 * 删除话题内容
	 * @param int $topic_id 话题ID
	 * @param int $question_id 话题关联类型ID
	 * 
	 * @return boolean true|false
	 */
	public function delete_topic($topic_id, $question_id, $competition_id, $action_log = true, $delete_record = false)
	{
		if (intval($topic_id) == 0)
		{
			return false;
		}
		
		$topic_info = $this->get_topic($topic_id);
		
		if ($question_id > 0)
		{
			$this->delete('topic_question', ' topic_id = ' . intval($topic_id) . ' AND question_id = ' . intval($question_id));
			
			if ($action_log)
			{
				ACTION_LOG::save_action(USER::get_client_uid(), $question_id, ACTION_LOG::CATEGORY_QUESTION, ACTION_LOG::DELETE_TOPIC, $topic_info['topic_title'], $topic_id);
				//ACTION_LOG::save_action(USER::get_client_uid(), $topic_id, ACTION_LOG::CATEGORY_TOPIC, ACTION_LOG::DELETE_TOPIC, $topic_info['topic_title'], $question_id);
			}
		}
		
		if ($question_id == 0)
		{
			$this->delete("topic_question", 'topic_id = ' . intval($topic_id));
			
			if ($action_log)
			{
				ACTION_LOG::save_action(USER::get_client_uid(), $topic_id, ACTION_LOG::CATEGORY_TOPIC, ACTION_LOG::DELETE_TOPIC, $topic_info['topic_title']);
			}
		}
		
		if ($delete_record)
		{
			$this->delete('topic', 'topic_id = ' . intval($topic_id));
		}
		
		return true;
	}

	/**
	 * 更新话题内容
	 * @param int    $topic_id             //话题ID
	 * @param string $topic_title       //话题标题
	 * @param string $topic_description //话题描述
	 * @param string $topic_pic         //话题图片
	 * @param int    $match_id             //比赛ID
	 * @param int    $discuss_count          //问题总数
	 *  
	 * @return boolean true|false
	 */
	public function update_topic($topic_id, $topic_title, $topic_description = '', $topic_pic = '', $discuss_count = 0, $topic_lock = 0)
	{
		$topic_title = htmlspecialchars(trim($topic_title));
		$topic_description = htmlspecialchars(trim($topic_description));
		$topic_pic = htmlspecialchars(trim($topic_pic));
		$discuss_count = intval($discuss_count);
		
		$topic_info = $this->get_topic($topic_id); //得到话题信息
		
		$data = array();
		
		if (! empty($topic_title))
		{
			$data['topic_title'] = $topic_title; 
		}
		if (! empty($topic_description))
		{
			$data['topic_description'] = $topic_description;
		}
		if (! empty($topic_pic))
		{
			$data['topic_pic'] = $topic_pic;
		}
		if ($discuss_count > 0)
		{
			$data['discuss_count'] = $discuss_count;
		}
		if (! empty($topic_lock))
		{
			$data['topic_lock'] = $topic_lock;
		}
		/*
		if ($is_top >= 0)
		{
			$data['is_top'] = $is_top;
		}
		*/
		/*
		if ($parent_id >= 0)
		{
			$data['parent_id'] = $parent_id;
		}
		*/
		
		if (count($data) > 0)
		{
			$this->update('topic', $data, 'topic_id = ' . intval($topic_id));
			
			//记录日志
			if ($topic_title && $topic_title != $topic_info['topic_title'])
			{
				ACTION_LOG::save_action(USER::get_client_uid(), $topic_id, ACTION_LOG::CATEGORY_TOPIC, ACTION_LOG::MOD_TOPIC, $topic_title, $topic_info['topic_title']);
			}
		
			if ($topic_description && $topic_description != $topic_info['topic_description'])
			{
				ACTION_LOG::save_action(USER::get_client_uid(), $topic_id, ACTION_LOG::CATEGORY_TOPIC, ACTION_LOG::MOD_TOPIC_DESCRI, $topic_description, $topic_info['topic_description']);
			}
		
			if ($topic_pic && $topic_pic != $topic_info['topic_pic'])
			{
				ACTION_LOG::save_action(USER::get_client_uid(), $topic_id, ACTION_LOG::CATEGORY_TOPIC, ACTION_LOG::MOD_TOPIC_PIC, $topic_pic, $topic_info['topic_pic']);
			}
		}
		
		return true;
	}

	/**
	 * 
	 * 锁定/解锁话题
	 * @param int $topic_id
	 * @param int $topic_lock
	 * 
	 * @return boolean true|false
	 */
	public function lock_topic_by_id($topic_id, $topic_lock = 0)
	{
		$topic_id = intval($topic_id);
		
		if ($topic_id == 0)
		{
			return false;
		}
		
		return $this->UPDATE('topic', array(
			'topic_lock' => $topic_lock
		), 'topic_id = ' . $topic_id);
	
	}

	/**
	 * 
	 * 删除话题
	 * @param int $topic_id
	 * @param int $uid
	 * 
	 * @return boolean true|false
	 */
	public function delete_topic_by_topic_id($topic_id, $uid)
	{
		ACTION_LOG::save_action(USER::get_client_uid(), $topic_id, ACTION_LOG::CATEGORY_TOPIC, ACTION_LOG::DELETE_TOPIC, '', $uid);
		
		return $this->delete('topic', ' topic_id = ' . intval($topic_id) . ' AND add_uid = ' . intval($uid));
	}

	/**
	 * 
	 * 修改话题分类,修改其父类即可
	 * @param int $topic_id
	 * @param int $topic_parent_id
	 * 
	 * @return boolean true|false
	 */
	public function change_topic_parent_id($topic_id, $topic_parent_id)
	{
		$topic_id = intval($topic_id);
		$topic_parent_id = intval($topic_parent_id);
		
		if ($topic_id == 0)
		{
			return false;
		}
		
		return $this->UPDATE('topic', array(
			'topic_parent_id' => $topic_parent_id
		), 'topic_id = ' . $topic_id);
	}

	/**
	 * 
	 * 判断话题是否锁定
	 * @param int $topic_id
	 * 
	 * @return boolean true|false
	 */
	public function has_lock_topic($topic_id)
	{
		$topic = $this->get_topic($topic_id);
		
		if ((isset($topic['topic_lock'])) && ($topic['topic_lock'] == 1))
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	/**
	 * 
	 * 判断是否存在相同话题
	 * @param string $topic_title
	 * 
	 * @return int topic_id
	 */
	public function has_topic($topic_title)
	{
		$topic = $this->get_topic_by_title($topic_title);
		
		if ((isset($topic['topic_id'])) && ($topic['topic_id'] > 0))
		{
			return $topic['topic_id'];
		}
		else
		{
			return 0;
		}
	}

	/**
	 * 
	 * 增加话题关注
	 * 
	 * @return boolean true|false
	 */
	public function add_focus_topic($uid, $topic_id)
	{
		if (! $this->has_focus_topic($uid, $topic_id))
		{
			$data = array(
				"topic_id" => intval($topic_id), 
				"uid" => intval($uid), 
				"add_time" => time()
			);
			
			if ($this->insert("topic_focus", $data))
			{
				$this->query('UPDATE ' . $this->get_table('topic') . " SET focus_count = focus_count + 1 WHERE topic_id = " . intval($topic_id));
			}
			
			$retval = 'add';
			
			//记录日志
			ACTION_LOG::save_action($uid, $topic_id, ACTION_LOG::CATEGORY_TOPIC, ACTION_LOG::ADD_TOPIC_FOCUS);
		}
		else
		{
			if ($this->delete_focus_topic($topic_id, $uid))
			{
				$this->query('UPDATE ' . $this->get_table('topic') . " SET focus_count = focus_count - 1 WHERE topic_id = " . intval($topic_id));
			}
			
			$retval = 'remove';
			
			//记录日志
			ACTION_LOG::save_action($uid, $topic_id, ACTION_LOG::CATEGORY_TOPIC, ACTION_LOG::DELETE_TOPIC_FOCUS);
		}
		
		//更新个人计数
		

		$focus_count = $this->count("topic_focus", 'uid = ' . intval($uid));
		
		$this->model("account")->update_users_fields(array(
			"topic_focus_count" => $focus_count
		), $uid);
		
		return $retval;
	}

	/**
	 * 
	 * 删除话题关注
	 * @param int/string $topic_id [1, 12]
	 * @param int $uid
	 * 
	 * @return boolean true|false
	 */
	public function delete_focus_topic($topic_id, $uid)
	{
		if (intval($topic_id) == 0)
		{
			return false;
		}
		
		return $this->delete('topic_focus', 'uid = ' . intval($uid) . ' AND topic_id = ' . intval($topic_id));
	
	}

	/**
	 * 
	 * 判断是否已经关注该话题
	 * @param int $uid
	 * @param int $topic_id
	 * 
	 * @return boolean true|false
	 */
	public function has_focus_topic($uid, $topic_id)
	{
		$sql = 'SELECT focus_id FROM ' . $this->get_table('topic_focus') . " WHERE uid = " . intval($uid) . " AND topic_id = " . intval($topic_id);
		
		$retval = $this->query_row($sql);
		
		return $retval['focus_id'];
	}

	/**
	 * 
	 * 增加/更新话题经验
	 * @param int    $topic_id
	 * @param int    $uid                //用户UID
	 * @param string $experience_content //话题经验内容
	 * 
	 * @return boolean true|false
	 */
	public function save_topic_experience($topic_id, $uid, $experience_content)
	{
		$topic_id = intval($topic_id);
		$uid = intval($uid);
		$experience_content = htmlspecialchars(trim($experience_content));
		
		if ($topic_id == 0 || $uid == 0 || $experience_content == '')
		{
			return false;
		}
		
		if ($this->has_topic_experience($uid, $topic_id))
		{
			
			$this->UPDATE("topic_experience", array(
				'experience_content' => $experience_content
			), 'uid = ' . intval($uid) . ' AND topic_id = ' . intval($topic_id));
			
			return 'UPDATE';
		}
		else
		{
			$data = array(
				'topic_id' => $topic_id, 
				'uid' => $uid, 
				'experience_content' => $experience_content, 
				'add_time' => time()
			);
			
			$this->insert('topic_experience', $data);
			
			return 'add';
		}
	}

	/**
	 * 
	 * 根据用户ID/话题ID,得到话题经验
	 * @param int $uid
	 * @param int $topic_id
	 * 
	 * @return boolean true|false
	 */
	public function get_topic_experience($uid, $topic_id)
	{
		$sql = 'SELECT experience_content FROM ' . $this->get_table('topic_experience') . " WHERE uid = " . intval($uid) . " AND topic_id = " . intval($topic_id);
		
		$retval = $this->query_row($sql);
		
		if (isset($retval['experience_content']))
		{
			return $retval['experience_content'];
		}
		else
		{
			return '';
		}
	}

	/**
	 * 
	 * 判断用户是否已经存在话题经验
	 * @param int $uid
	 * @param int $topic_id
	 * 
	 * @return boolean true|false
	 */
	public function has_topic_experience($uid, $topic_id)
	{
		$sql = 'SELECT experience_id FROM ' . $this->get_table('topic_experience') . " WHERE uid = " . intval($uid) . " AND topic_id = " . intval($topic_id);
		
		$retval = $this->query_row($sql);
		
		if (isset($retval['experience_id']) && $retval['experience_id'] > 0)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	/**
	 * 
	 * 得到用户不感兴趣话题列表
	 * @param int $uid
	 * 
	 * @return array
	 */
	public function get_uninterested_list_by_uid($uid)
	{
		return $this->query_all('SELECT topic_id FROM ' . $this->get_table('topic_uninterested') . " WHERE uid = " . intval($uid));
	}

	/**
	 * 
	 * 不感兴趣话题
	 * @param int $uid
	 * @param int $topic_id
	 * 
	 * @return boolean
	 */
	public function save_topic_uninterested($uid, $topic_id)
	{
		if (! $this->has_topic_uninterested($uid, $topic_id))
		{
			$this->insert("topic_uninterested", array(
				'uid' => $uid, 
				'topic_id' => intval($topic_id), 
				'add_time' => time()
			));
			
			return true;
		}
		
		return false;
	}

	/**
	 * 
	 * 判断用户是否已经不感兴趣话题
	 * @param int $uid
	 * @param int $topic_id
	 * 
	 * @return boolean
	 */
	public function has_topic_uninterested($uid, $topic_id)
	{
		$sql = 'SELECT uid FROM ' . $this->get_table('topic_uninterested') . " WHERE uid = " . intval($uid) . " AND topic_id = " . intval($topic_id);
		
		$retval = $this->query_row($sql);
		
		if (isset($retval['uid']) && $retval['uid'] > 0)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	function get_topic_by_parent_id($count, $parent_id)
	{
		$parent_id = intval($parent_id);
		
		if ($parent_id < 0)
		{
			return false;
		}
		
		if ($parent_id >= 0)
		{
			$where[] = "parent_id = " . $parent_id;
		}
		if ($parent_id == 0)
		{
			$where[] = "is_top = 1";
		}
		
		if ($count)
		{
			return $this->count('topic', implode(' AND ', $where));
		}
		
		return $this->fetch_all('topic', implode(' AND ', $where), 'topic_id ASC');
	}

	function get_position_by_id($topic_id, $position = array())
	{
		$topic_id = intval($topic_id);
		$rs = $this->get_topic($topic_id);
		
		if (is_array($rs))
		{
			$data['topic_id'] = $rs['topic_id'];
			$data['topic_title'] = $rs['topic_title'];
			$data['parent_id'] = $rs['parent_id'];
			$position[] = $data;
		}
		
		if ($data['parent_id'] == 0 || COUNT($position) > 3)
		{
			return array_reverse($position);
		}
		else if ($data['parent_id'] > 0)
		{
			return $this->get_position_by_id($data['parent_id'], $position);
		}
	}

	/**
	 * 更新问题统计
	 * @param  $topic_id
	 */
	function update_discuss_count($topic_id)
	{		
		if (! $topic_id)
		{
			return false;
		}
		
		return $this->query("UPDATE " . $this->get_table('topic') . " SET discuss_count = (SELECT COUNT(*) FROM " . $this->get_table('topic_question') . " WHERE topic_id = " . intval($topic_id) . ") WHERE topic_id = " . intval($topic_id));
	}
	
	function update_all_discuss_count()
	{
		$topics = $this->query_all("SELECT topic_id FROM " . $this->get_table('topic'));
		
		foreach ($topics AS $key => $val)
		{
			$this->query("UPDATE " . $this->get_table('topic') . " SET discuss_count = (SELECT COUNT(*) FROM " . $this->get_table('topic_question') . " WHERE topic_id = " . $val['topic_id'] . ") WHERE topic_id = " . $val['topic_id']);
		}
	}
	
	/**
	 * 物理删除话题及其关联的图片等
	 * 
	 * @param  $topic_id
	 */
	public function remove_topic($topic_id)
	{
		$topic_id = intval($topic_id);
		
		if (! $topic_id)
		{
			return false;
		}
		
		$topic_info = $this->get_topic($topic_id);
		
		//删除与问题、比赛的关联及其动作
		$this->delete('topic_question', 'topic_id = ' . $topic_id);
		
		//删除话题图片
		// 		$thumb_sizes = array(
		// 			'350_350', 
		// 			'150_150', 
		// 			'50_50'
		// 		);
		

		if ($topic_info['topic_pic'])
		{
			foreach (AWS_APP::config()->get('image')->topic_thumbnail as $size)
			{
				
				unlink(get_setting('upload_dir') . '/topic/' . str_replace(AWS_APP::config()->get('image')->topic_thumbnail['min']['w'] . '_' . AWS_APP::config()->get('image')->topic_thumbnail['min']['h'], $size['w'] . '_' . $size['h'], $topic_info['topic_pic']));
			
			}
			
			@unlink(get_setting('upload_dir') . '/topic/' . $topic_info['topic_pic']);
		}
		
		//删除关注		
		$this->delete('topic_focus', 'topic_id = ' . $topic_id);
		
		//删除不感兴趣的
		$this->delete('topic_uninterested', 'topic_id = ' . $topic_id);
		
		//删除动作	
		ACTION_LOG::delete_action_history("associate_type = 4 AND associate_id = " . $topic_id);
		ACTION_LOG::delete_action_history("associate_type IN (1, 5) AND associate_action = 401 AND associate_attached = " . $topic_id);
		
		//删除话题		
		return $this->delete('topic', 'topic_id=' . $topic_id);
	
	}

	public function get_topic_list_v2($limit, $order = 'topic_id DESC', $where = false)
	{
		return $this->fetch_all('topic', $where, $order, $limit);
	}
	
	// 我关注的人关注的话题
	public function get_user_recommend_v2($uid, $limit = 10)
	{
		
		$my_focus = array(
			0
		);
		
		if ($get_my_focus = $this->query_all("SELECT topic_id FROM " . $this->get_table("topic_focus") . " WHERE uid = " . (int)$uid))		
		{
			foreach ($get_my_focus as $key => $val)
			{
				$my_focus[] = $val['topic_id'];
			}
		}
		
		if ($friends = $this->model('follow')->get_user_friends($uid, false))
		{
			foreach ($friends as $key => $val)
			{
				$follow_uids[] = $val['friend_uid'];
				$follow_users_array[$val['friend_uid']] = $val;
			}
		}
		if (! $follow_uids)
		{
			return $this->get_topic_list_v2($limit, 'topic_id DESC', "topic_id NOT IN(" . implode($my_focus, ',') . ")");
		}
		
		if ($topic_focus = $this->query_all("SELECT DISTINCT topic_id, uid FROM " . $this->get_table("topic_focus") . " WHERE uid IN(" . implode($follow_uids, ',') . ") AND topic_id NOT IN (" . implode($my_focus, ',') . ") ORDER BY focus_id DESC LIMIT " . $limit))
		{
			foreach ($topic_focus as $key => $val)
			{
				$topic_ids[] = $val['topic_id'];
				$topic_id_focus_uid[$val['topic_id']] = $val[uid];
			}
		}
		if (! $topic_ids)
		{
			return $this->get_topic_list_v2($limit, 'topic_id DESC', "topic_id NOT IN (" . implode($my_focus, ',') . ")");
		}
		
		$topics = $this->query_all("SELECT * FROM " . $this->get_table('topic') . " WHERE topic_id IN(" . implode($topic_ids, ',') . ") AND topic_id NOT IN (" . implode($my_focus, ',') . ") ORDER BY topic_id DESC LIMIT " . $limit);

		
		foreach ($topics as $key => $val)
		{
			$topics[$key]['focus_users'] = $follow_users_array[$topic_id_focus_uid[$val['topic_id']]];
		}
		
		return $topics;
	}

	function get_focus_users_by_topic($topic_id, $limit = 19)
	{
		
		$users_list = array();
		
		if ($uids = $this->query_all("SELECT DISTINCT uid FROM {$this->get_table("topic_focus")} WHERE topic_id = " . intval($topic_id), $limit))		
		{
			foreach ($uids as $key => $user)
			{
				$user_info = $this->model('account')->get_users_by_uid($user['uid']);
				
				if ($user_info['uid'])
				{
					$users_list[$user_info['uid']] = array(
						'uid' => $user_info['uid'],
						'avatar_file' => $user_info['avatar_file'],
						'user_name' => $user_info['user_name']
					);
				}
			}
		}
		return $users_list;
	}

	function get_all_by_topic($topic_id, $limit = 10)
	{
		$query = "SELECT t.*, q.published_uid AS q_published_uid, q.add_time AS q_add_time, q.* FROM {$this->get_table("topic_question")} AS t LEFT JOIN {$this->get_table("question")} AS q ON t.question_id = q.question_id  WHERE t.question_id>0 AND  t.topic_id = " . intval($topic_id) . " ORDER BY q.modify_time DESC";
		
		if ($result = $this->query_all($query, $limit))
		{
			foreach ($result as $key => $data)
			{
				if ($data['question_id'])
				{
					$data['published_uid'] = $data['q_published_uid'];
					$result[$key]['published_uid'] = $data['q_published_uid'];
					
					$answer_list = $this->model('answer')->get_answer_list_by_question_id($data['question_id'], 1);
					
					if (! isset($user_list[$data['published_uid']]))
					{
						$user_list[$data['published_uid']] = $this->model('account')->get_users($data['published_uid']);
					}
					
					$result[$key]['title'] = $data['question_content'];
					$result[$key]['focus'] = $this->model('question')->has_focus_question($data['question_id'], $this->user_id);
					$result[$key]['topics'] = $this->model('question_topic')->get_question_topic_by_question_id($data['question_id']);
					$result[$key]['vote_count'] = $answer_list[0]['agree_count'];
					$result[$key]['pic'] = $user_list[$data['published_uid']]['avatar_file'];
					$result[$key]['name'] = $user_list[$data['published_uid']]['name'];
					$result[$key]['answer'] = $answer_list[0];
					$result[$key]['question_id'] = $data['question_id'];
					$result[$key]['add_time'] = $data['q_add_time'];
					$result[$key]['answer_count'] = $data['answer_count'];
					$result[$key]['user_info'] = $user_list[$data['published_uid']];
				}
			
			}
		}
		
		return $result;
	}

	/**
	 * 新版获取
	 * @param  $topic_id
	 * @param  $limit
	 */
	function get_all_by_topic_v2($topic_id, $limit = 10)
	{
		$query = "SELECT t.*, q.published_uid AS q_published_uid, q.add_time AS q_add_time, q.* FROM {$this->get_table("topic_question")} AS t LEFT JOIN {$this->get_table("question")} AS q ON t.question_id = q.question_id  WHERE t.question_id>0 AND t.topic_id = " . intval($topic_id);
		
		return $this->query_all($query, $limit);
	}
	
	/**
	 * 新版获取
	 * @param  $topic_id
	 * @param  $limit
	 */
	function get_all_best_question_by_topic($topic_id, $limit = 10,$count=false)
	{
       
		if ($count==true)
		{
			$query = "SELECT COUNT(*) as COUNT FROM {$this->get_table("topic_question")} AS t LEFT JOIN {$this->get_table("question")} AS q ON t.question_id = q.question_id  WHERE t.question_id > 0 AND q.best_answer > 0 AND t.topic_id = " . intval($topic_id);
			
			$rs=$this->query_all($query);
			
			
			return $rs[0]['COUNT'];
		}
		else
		{
			$query = "SELECT  q.* FROM {$this->get_table("topic_question")} AS t LEFT JOIN {$this->get_table("question")} AS q ON t.question_id = q.question_id  WHERE t.question_id > 0 AND q.best_answer > 0 AND  t.topic_id = " . intval($topic_id);
	
			return $this->query_all($query, $limit);
		}
	}	

	function get_question_ids_by_topic($topic_id, $limit = 10)
	{
		$query = "SELECT question_id FROM {$this->get_table("topic_question")} WHERE question_id > 0 AND  topic_id = " . intval($topic_id);
		
		return $this->query_all($query, $limit);
	}

	public function modify_pic_topic_by_id($topic_id, $topic_pic)
	{
		$topic_id = intval($topic_id);
		
		if ($topic_id == 0)
		{
			return false;
		}
		
		if (empty($topic_pic))
		{
			return false;
		}
		
		return $this->update_topic($topic_id, '', '', $topic_pic, '', '');
	}

	/**
	 * 获取最佳回复者,对于本话题
	 * @param  $topic_id
	 */
	public function get_best_answer_list($topic_id, $uid)
	{
		if (! $question_ids = $this->get_question_ids_by_topic($topic_id, false))
		{
			return;
		}
		
		foreach ($question_ids as $key => $val)
		{
			$question_id_array[] = $val['question_id'];
		}
		
		if (! $users_anwser = $this->model('answer')->get_answers(false, "question_id IN(" . implode(',', $question_id_array) . ")"))
		{
			return;
		}
		
		$reputation_function = get_setting('reputation_function');
		
		$best_answer_users = array();
		
		$user_answer_question = array();
		
		foreach ($users_anwser as $key => $val)
		{
			
			$anwser[] = $val['answer_id'];
		}
		
		if ($anwser)
		{
			$vote_users_agrees = $this->model('answer')->get_vote_agree_by_answer_ids($anwser);
			$vote_users_against = $this->model('answer')->get_vote_against_by_answer_ids($anwser);
		}
		
		$best_answer_reput = get_setting('best_answer_reput');
		$publisher_reputation_factor = get_setting('publisher_reputation_factor');
		
		foreach ($users_anwser as $key => $an_val)
		{
			$answer_question_ids[] = $an_val['question_id'];
		}
		
		if ($answer_question_ids)
		{
			$answer_questions = $this->model('question')->get_question_info_by_ids($answer_question_ids);
		}
	
		foreach ($users_anwser as $key => $an_val)
		{
			$user_answer_question[$an_val['uid']][$an_val['question_id']] = $an_val['question_id'];
			
			$answer_id = $an_val['answer_id'];
			$question_id = $an_val['question_id'];
			
			$s_best_answer = 0;
			$s_agree_count = 0;
			$s_against_count = 0;
			$s_initiate_agree_count = 0;
			$s_initiate_against_count = 0;
			$tmp_reputation = 0;
			
			if (! $answer_questions[$question_id])
			{
				continue;
			}
			
			if ($answer_questions[$question_id]['best_answer'] == $answer_id)
			{
				$s_best_answer = 1;
			}
			
			$s_agree_count = 0;
			$s_against_count = 0;
			
			if ($vote_users_agrees[$answer_id])
			{
				foreach ($vote_users_agrees[$answer_id] as $vote_uid => $vote_val)
				{
					if ($answer_questions[$question_id]['published_uid'] == $vote_uid)
					{
						continue;
					}
										
					$s_agree_count += $s_agree_count + $vote_val['reputation_factor'];
				}
				
				if (array_key_exists($answer_questions[$question_id]['published_uid'], $vote_users_agrees[$answer_id]))
				{
					$s_initiate_agree_count = 1;
				}
			}
			
			if ($vote_users_against[$answer_id])
			{
				foreach ($vote_users_against[$answer_id] as $vote_key => $vote_val)
				{
					if ($answer_questions[$question_id]['published_uid'] == $vote_val['uid'])
					{
						continue;
					}
						
					$s_against_count += $s_against_count + $vote_val['reputation_factor'];
				
				}
				
				if (array_key_exists($answer_questions[$question_id]['published_uid'], $vote_users_against[$answer_id]))
				{
					$s_initiate_against_count = 1;
				}
			}
			
// 		
			$tmp_reputation = $s_best_answer * $best_answer_reput + $s_agree_count - $s_against_count + $s_initiate_agree_count * $publisher_reputation_factor - $s_initiate_against_count * $publisher_reputation_factor;
				
			$tmp_reputation = log($tmp_reputation, 3);
		
			if (intval($tmp_reputation) <= 0)
			{
				$tmp_reputation = 0;
			}
			
			$best_answer_users[$an_val['uid']]['uid'] = $an_val['uid'];
			$best_answer_users[$an_val['uid']]['reputation'] = intval($best_answer_users[$an_val['uid']]['reputation']) + $tmp_reputation;
			$best_answer_users[$an_val['uid']]['agree_count'] = intval($best_answer_users[$an_val['uid']]['agree_count']) + $an_val['agree_count'];
			$best_answer_users[$an_val['uid']]['question_count'] = count($user_answer_question[$an_val['uid']]);
		
		}
		
		if ($best_answer_users)
		{
			foreach($best_answer_users as $key=>$val)
			{
					if ($val['agree_count']<=0)
					{
						unset($best_answer_users[$key]);//过滤到空赞成的
					}
					else
					{
						$uids[] = $val['uid'];
					}							
			}
		}
		
		if (!is_array($uids))
		{
			return array();			
		}
		
		$users_list = $this->model("account")->get_users_list('MEM.uid IN (' . implode(',', $uids) . ')', null, true, false);
		
		foreach ($users_list as $key => $val)
		{			
			$best_answer_users[$val['uid']]['user_info'] = $val;	
			$best_answer_users[$val['uid']]['user_info']['focus'] = $this->model('follow')->user_follow_check($uid, $val['uid']);		
		}
		
		$best_answer_users = aasort($best_answer_users, array(
			'-reputation'
		));
		
		return $best_answer_users;
	}

	/**
	 * 获取 分类 的热门话题
	 * @param  $category
	 */
	public function get_hot_topic($category_id = 0, $add_time = 0, $limit = 5, $count = false)
	{
		$day = 30;
		
		if ($add_time == 0)
		{
			$add_time = time() - 60 * 60 * 24 * $day; //只处理30天内的(可调)
		}
		
		if ($category_id)
		{
			$question_all = $this->fetch_all('question', "add_time > " . $add_time . " AND category_id IN(" . implode(',', $this->model('system')->get_category_with_child_ids('question', $category_id)) . ')');
		}
		else
		{
			$question_all = $this->fetch_all('question', "add_time > " . $add_time);
		}
		
		if ($question_all)
		{
			foreach ($question_all as $key => $val)
			{
				$question_ids[] = $val['question_id'];
				$question_focus_count[$val['question_id']] = $val['focus_count'];
				$question_answer_count[$val['question_id']] = $val['answer_count'];
			}
		}
		
		//取话题
		if ($question_ids)
		{
			$sql = 'SELECT tp.topic_id,t.topic_description,tp.question_id,t.focus_count,t.topic_title,t.topic_pic,t.discuss_count,t.focus_count  FROM ' . $this->get_table('topic_question') . ' tp LEFT JOIN ' . $this->get_table('topic') . ' t ON tp.topic_id=t.topic_id  WHERE question_id in (' . implode(",", $question_ids) . ') ';
		}
		else
		{
			return array();
		}
		
		if ($rs = $this->query_all($sql))
		{
			foreach ($rs as $key => $val)
			{
				$topics[$val['topic_id']]['topic_id'] = $val['topic_id'];
				$topics[$val['topic_id']]['focus_count'] = $val['focus_count'];
				$topics[$val['topic_id']]['discuss_count'] = $val['discuss_count'];
				$topics[$val['topic_id']]['topic_title'] = $val['topic_title'];
				$topics[$val['topic_id']]['topic_description'] = $val['topic_description'];
				$topics[$val['topic_id']]['topic_pic'] = $val['topic_pic'];
				$topics[$val['topic_id']]['question_focus_count'] = $topics[$val['topic_id']]['question_focus_count'] + $question_focus_count[$val['question_id']];
				//$topics[$val['topic_id']]['question_answer_count']=$topics[$val['topic_id']]['question_answer_count']+$question_answer_count[$val['question_id']];
				$topics[$val['topic_id']]['question_count'] = intval($topics[$val['topic_id']]['question_count']) + 1;
				$topics[$val['topic_id']]['scores'] = $topics[$val['topic_id']]['focus_count'] + $topics[$val['topic_id']]['question_count'];
			}
		}
		
	
		if (is_array($topics))
		{
			$topics = aasort($topics, array(
				'-scores'
			));
			
			$topics_count = count($topics);
			
			if ($topics)
			{
				if (strstr($limit, ','))
				{
					$limit = explode(',', $limit, 2);
					
					$topics = array_slice($topics, $limit[0], $limit[1]);
				}
				else
				{
					$topics = array_slice($topics, 0, $limit);
				}
				
				return array(
					'topics' => $topics, 
					'topics_count' => $topics_count
				);
			}
			else
			{
				return array(
					'topics' => array(), 
					'topics_count' => 0
				);
			
			}
		}
	}

	/**
	 * 获取 分类 的话题
	 * @param  $category
	 */
	public function get_category_topic($category_id = 0, $add_time = 0, $limit = 5, $count = false)
	{
		
		//取话题
		if ($count == true)
		{
			$sql = 'SELECT COUNT(*) AS count FROM ' . $this->get_table('topic') . ' WHERE topic_id IN (SELECT tq.topic_id FROM  ' . $this->get_table('topic_question') . ' tq LEFT JOIN ' . $this->get_table('question') . ' q ON tq.question_id = q.question_id WHERE q.category_id = ' . intval($category_id) . ')';
			
			$rs = $this->query_row($sql);
			
			return $rs['count'];
		}
		else
		{
			$sql = 'SELECT * FROM ' . $this->get_table('topic') . ' WHERE topic_id IN (SELECT tq.topic_id FROM ' . $this->get_table('topic_question') . ' tq LEFT JOIN ' . $this->get_table('question') . ' q ON tq.question_id = q.question_id WHERE q.category_id = ' . $category_id . ')';
			
			$rs = $this->query_all($sql);
			
			return $rs;
		}
	}
	
	/**
	 * 获取 分类 的最新话题
	 * @param  $category
	 */
	public function get_category_new_topic($category_id = 0, $add_time = 0, $limit = 5, $count = false)
	{
		//取话题
		if ($count == true)
		{
			$sql = 'SELECT COUNT(*) AS COUNT FROM ' . $this->get_table('topic') . ' WHERE topic_id IN (SELECT tq.topic_id FROM ' . $this->get_table('topic_question') . ' tq LEFT JOIN ' . $this->get_table('question') . ' q ON tq.question_id = q.question_id WHERE q.category_id = ' . intval($category_id) . ')';	
						
			$rs = $this->query_row($sql);
				
			return $rs['COUNT'];
		}
		else
		{
			if ($add_time > 0)
			{
				$sql = 'SELECT * FROM ' . $this->get_table('topic') . ' WHERE topic_id IN (SELECT tq.topic_id FROM  ' . $this->get_table('topic_question') . ' tq LEFT JOIN ' . $this->get_table('question') . ' q ON tq.question_id = q.question_id WHERE q.category_id = ' . intval($category_id) . ') WHERE add_time > ' . $add_time . ' ORDER BY add_time DESC';
			}
			else				
			{
				$sql = 'SELECT * FROM ' . $this->get_table('topic') . ' WHERE topic_id IN (SELECT tq.topic_id FROM  ' . $this->get_table('topic_question') . ' tq LEFT JOIN ' . $this->get_table('question') . ' q ON tq.question_id=q.question_id WHERE q.category_id = ' . intval($category_id) . ') ORDER BY add_time DESC';				
			}
			
			$rs = $this->query_all($sql,$limit);
			
			return $rs;
		}
	
	}	

	/**
	 * 处理话题日志
	 * @param array $log_list
	 * 
	 * @return array
	 */
	public function analysis_log($log_list)
	{
		$data_list = array();
		$uid_list = array(
			0
		);
		$topic_list = array(
			0
		);
		
		if (empty($log_list))
		{
			return;
		}
		/**
		 * 找到唯一数据值
		 */
		foreach ($log_list as $key => $log)
		{
			
			if (! in_array($log['uid'], $uid_list))
			{
				$uid_list[] = $log['uid'];
			}
			if (! empty($log['associate_attached']) && is_numeric($log['associate_attached']) && ! in_array($log['associate_attached'], $topic_list))
			{
				$topic_list[] = $log['associate_attached'];
			}
			if (! empty($log['associate_content']) && is_numeric($log['associate_content']) && ! in_array($log['associate_content'], $topic_list))
			{
				$topic_list[] = $log['associate_content'];
			}
		}
		
		/**
		 * 格式话简单数据类型
		 */
		
		if ($topic_title_array = $this->model('topic')->get_topic_title($topic_list))
		{
			foreach ($topic_title_array as $topic_title_info)
			{
				$topic_title_list[$topic_title_info['topic_id']] = $topic_title_info['topic_title'];
			}
		}
		//格式化用户名
		if ($user_name_array = $this->model('account')->get_users_by_uids($uid_list))
		{
			foreach ($user_name_array as $user_info)
			{
				$user_info_list[$user_info['uid']] = $user_info['user_name'];
			}
		}

		
		/**
		 * 格式话数组
		 */
		foreach ($log_list as $key => $log)
		{
			$title_list = "";
			$user_name = $user_info_list[$log['uid']];
			$user_url = 'people/'.$user_info_list[$log['uid']];
			
			switch ($log['associate_action'])
			{
				case ACTION_LOG::ADD_TOPIC : //增加话题
					$title_list = '<a href="' . $user_url . '">' . $user_name . '</a> 创建了该话题</p>';
					break;
				
				case ACTION_LOG::ADD_TOPIC_FOCUS : //关注话题
					

					break;
				
				case ACTION_LOG::DELETE_TOPIC : //删除话题
					

					break;
					
				case ACTION_LOG::DELETE_TOPIC_FOCUS : //删除话题关注
					

					break;
				
				case ACTION_LOG::MOD_TOPIC : //修改话题标题
					$Services_Diff = new Services_Diff($log['associate_attached'], $log['associate_content']);
					
					$title_list = '<a href="' . $user_url . '">' . $user_name . '</a> 修改了话题 <a href="topic/'. $log['associate_content'] . '"></a> 标题 <p>' . $Services_Diff->get_Text_Diff_Renderer_inline() . "</p>";
					break;
				
				case ACTION_LOG::MOD_TOPIC_DESCRI : //修改话题描述
					$log['associate_attached'] = trim($log['associate_attached']);
					$log['associate_content'] = trim($log['associate_content']);

					$Services_Diff = new Services_Diff($log['associate_attached'], $log['associate_content']);
					$title_list = '<a href="' . $user_url . '">' . $user_name . '</a> 修改了话题描述<p>' . $Services_Diff->get_Text_Diff_Renderer_inline() . '</p>';
					
					break;
				
				case ACTION_LOG::MOD_TOPIC_PIC : //修改话题图片
					$title_list = '<a href="' . $user_url . '">' . $user_name . '</a> 修改了话题图片';
					break;
				
				case ACTION_LOG::ADD_RELATED_TOPIC : //添加相关话题
					$topic_info = $this->model('topic')->get_topic($log['associate_attached']);
					
					$title_list = '<a href="' . $user_url . '">' . $user_name . '</a> 添加了相关话题<p><a href="topic/' . $topic_info['topic_title'] . '">' . $topic_info['topic_title'] . '</a></p>';
					break;
				
				case ACTION_LOG::DELETE_RELATED_TOPIC : //删除相关话题
					$topic_info = $this->model('topic')->get_topic($log['associate_attached']);
					
					$title_list = '<a href="' . $user_url . '">' . $user_name . '</a> 删除了相关话题<p><a href="topic/' . $topic_info['topic_title'] . '">' . $topic_info['topic_title'] . '</a></p>';
					break;
			}
			
			(! empty($title_list)) ? $data_list[] = array(
				'user_name' => $user_name, 
				'title' => $title_list, 
				'add_time' => date('Y-m-d', $log['add_time']), 
				'log_id' => sprintf('%06s', $log['history_id'])
			) : '';
		}
	
		return $data_list;
	}
	
	public function save_related_topic($topic_id, $related_id)
	{
		$this->pre_save_auto_related_topics($topic_id);
		
		if (!$related_topic = $this->fetch_row('related_topic', 'topic_id = ' . intval($topic_id) . ' AND related_id = ' . intval($related_id)))
		{
			return $this->insert('related_topic', array(
				'topic_id' => intval($topic_id),
				'related_id' => intval($related_id)
			));
		}
		
		return false;
	}
	
	public function remove_related_topic($topic_id, $related_id)
	{
		$this->pre_save_auto_related_topics($topic_id);
		
		return $this->delete('related_topic', 'topic_id = ' . intval($topic_id) . ' AND related_id = ' . intval($related_id));
	}
	
	public function pre_save_auto_related_topics($topic_id)
	{
		if (!$this->is_user_related($topic_id))
		{
			if ($auto_related_topics = $this->get_auto_related_topics($topic_id))
			{
				foreach ($auto_related_topics AS $key => $val)
				{
					$this->insert('related_topic', array(
						'topic_id' => intval($topic_id),
						'related_id' => $val['topic_id']
					));
				}
			}
			
			$this->update('topic', array(
				'user_related' => 1
			), 'topic_id = ' . intval($topic_id));
		}
	}
	
	public function get_related_topics($topic_id)
	{
		if ($related_topic = $this->fetch_all('related_topic', 'topic_id = ' . intval($topic_id)))
		{
			foreach ($related_topic AS $key => $val)
			{
				$topic_ids[] = $val['related_id'];
			}
		}
		
		if ($topic_ids)
		{
			return $this->get_topics($topic_ids);
		}
	}
	
	public function get_auto_related_topics($topic_id)
	{
		if ($questions_topics = $this->get_question_ids_by_topic($topic_id))
		{
			foreach ($questions_topics AS $key => $val)
			{
				$question_ids[] = $val['question_id'];
			}
		}
		
		if ($question_ids)
		{
			if ($topics = $this->model('question_topic')->get_question_topic_by_question($question_ids, 10))
			{
				foreach ($topics as $key => $val)
				{
					if ($val['topic_id'] == $topic_id)
					{
						unset($topics[$key]);
					}
				}
				
				return $topics;	
			}
		}
	}
	
	public function related_topics($topic_id)
	{
		if ($this->is_user_related($topic_id))
		{
			$related_topic = $this->get_related_topics($topic_id);
		}
		else
		{
			$related_topic = $this->get_auto_related_topics($topic_id);
		}
		
		return $related_topic;
	}
	
	public function is_user_related($topic_id)
	{
		$topic = $this->get_topic($topic_id);
		
		return $topic['user_related'];
	}
}